package cn.s1995.sloth.common.core.convert;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * NumberFormatConvert
 *
 * @author Lex
 * @description 数字格式化转换器
 * @date 2024/01/17 15:36
 */
public class NumberFormatConvert extends JsonSerializer<Number> {
    @Override
    public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (number == null) {
            jsonGenerator.writeString(StrUtil.EMPTY);
            return;
        }

        jsonGenerator.writeString(formatNumber(number.longValue()));
    }

    private static String formatNumber(long number) {
        if (number < 1000) {
            return String.valueOf(number);
        } else if (number < 1000000) {
            return String.format("%.1fK", number / 1000.0);
        } else {
            return String.format("%.1fM", number / 1000000.0);
        }
    }

    public static void main(String[] args) {
        System.out.println(formatNumber(999));    // 输出: 999
        System.out.println(formatNumber(1000));   // 输出: 1.0K
        System.out.println(formatNumber(27300));  // 输出: 27.3K
        System.out.println(formatNumber(103000)); // 输出: 103.0K
        System.out.println(formatNumber(7200000));// 输出: 7.2M
    }
}
